package cc.rengu.oltp.service.base;

import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.realize.RiskMonitorService;
import cc.rengu.oltp.utility.util.StringUtil;
import cc.rengu.oltp.utility.util.XmlTreeUtil;

import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
import java.util.Map;

/**
 * 风险监控及告警推送服务
 * Created by wangcheng on 2021/10/15 9:55
 */
public class MonitorRiskAlarmService extends RadpService {
    @Override
    protected int bizInit(String s) {
        return 0;
    }

    @Override
    protected int bizProcess(String s, int i) {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        try {
            String exceptionMsg = xmlTreeUtil.getXmlTreeStringValue(AppParamConstant.EXCEPTION_MSG);
            String className = xmlTreeUtil.getXmlTreeStringValue(AppParamConstant.RISK_MONITOR_INFO);
            String monitorPushFlag = xmlTreeUtil.getXmlTreeStringValue(AppParamConstant.MONITOR_PUSH_FLAG);
            String alarmPushFlag = xmlTreeUtil.getXmlTreeStringValue(AppParamConstant.ALARM_PUSH_FLAG);
            String riskCollectFlag = xmlTreeUtil.getXmlTreeStringValue(AppParamConstant.RISK_COLLECT_FLAG);
            if (!StringUtil.isEmptyOrNull(className)) {
                rglog.info("风险监控告警实现类:{}", className);
                RiskMonitorService riskMonitorService = (RiskMonitorService) Class.forName(className).newInstance();
                /* Step1：获取熔断控制信息 */
                if (AppParamConstant.YES.equals(monitorPushFlag)) {
                    rglog.info("---------------> 推送交易监控信息 <---------------");
                    riskMonitorService.monitorPush();
                }
                if (AppParamConstant.YES.equals(alarmPushFlag)) {
                    rglog.info("---------------> 推送交易告警信息 <---------------");
                    riskMonitorService.alarmPush(exceptionMsg);
                }
                if (AppParamConstant.YES.equals(riskCollectFlag)) {
                    rglog.info("---------------> 推送交易风控采集信息 <---------------");
                    Map<String, String> message = (Map<String, String>) xmlTreeUtil.getXmlTreeObjectValue(AppParamConstant.ALARM_MSG, Map.class);
                    riskMonitorService.riskCollectPush(message);
                }
            }
        } catch (Exception e) {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            e.printStackTrace(new PrintWriter(byteArrayOutputStream, true));
            rglog.error("风险监控及告警服务处理失败，异常信息:<{}>", byteArrayOutputStream.toString());
            return -1;
        }
        return 0;
    }

    @Override
    protected int bizTerminate(String s) {
        return 0;
    }
}
